package com.wp.rcm.controller;

import com.wp.rcm.pojo.User;
import com.wp.rcm.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Controller
public class UserController {

    @Resource
    private UserService userService;

    @GetMapping("/toLogin")
    public String toLogin() {
        return "login";
    }

    @PostMapping("/doLogin")
    public String Login(String usrName, String usrPassword, HttpSession session, Model model) {

        /**
         *  UsernamePasswordToken token = new UsernamePasswordToken(usrName,usrPassword);
         *         Subject subject = SecurityUtils.getSubject();
         *         try {
         *             subject.login(token); //调用shiro认证
         *             //保存登入的信息==>通过shiro中认证的身份
         *             User loginUser = (User) subject.getPrincipal();
         *             session.setAttribute("loginUser", loginUser);
         *
         *         }catch (UnknownAccountException e){
         *             return "redirect:/chance/toLogin";
         *         }catch (LockedAccountException e1){
         *             return "";
         *         }
         *         return "redirect:/chance/main";
         */
        try {
            UsernamePasswordToken token = new UsernamePasswordToken(usrName,usrPassword);

            Subject subject = SecurityUtils.getSubject();
            subject.login(token); // 认证、登录

            // 认证登陆成功
            User user = (User) subject.getPrincipal();
            session.setAttribute("loginUser",user);
            return "redirect:/main";
        }catch (UnknownAccountException | IncorrectCredentialsException e){
            model.addAttribute("msg","用户名或密码错误，登陆失败");
            return "login";
        }catch (LockedAccountException e){
            model.addAttribute("msg","用户被禁用，请重新登录");
            return "login";
        }catch (AuthenticationException e){
            model.addAttribute("msg","认证异常，登陆失败");
            return "login";
        }
    }

    @GetMapping("/main")
    public String findAll() {

        return "main";
    }


    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("loginUser");
        SecurityUtils.getSubject().logout();
        return "redirect:/main";
    }

    @RequestMapping(value = "/403")
    public String unautohorized(){
        return "403";
    }
}
